//
//  AddSectionListController.m
//  NewsReader
//
//  Created by blacksun on 10-10-31.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "AddSectionListController.h"


@implementation AddSectionListController

@synthesize tableView,enableSections,selectedSection;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	NSMutableArray *temp = [[NSMutableArray alloc] init];
	self.enableSections = temp;
	[temp release];
	self.tableView.delegate = self;
	self.tableView.dataSource = self;
	
	NSMutableDictionary *array = [[NSMutableDictionary alloc] init];
	self.selectedSection = array;
	[array release];
	
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	NSLog(@"enable sections...");
	NSURL *url = [[NSURL alloc] initWithString:[URLAddress listAllSections]];
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	
	HttpUtil *httpUtil = [[HttpUtil alloc] init];
	[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishHttpRequest:) isBackGround:YES];
	[httpUtil release];
	[request release];
	[url release];
	
}
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
-(void) finishHttpRequest:(NSMutableData *)responseData{
	NSString *responseStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	NSDictionary * responseDict = [responseStr JSONValue];
	NSArray *sectionsArray = [responseDict objectForKey:@"sections"];
	NSArray *inServerSections =  [ModelParseUtil parseSectionsFromJsonArray:sectionsArray];
	[responseStr release];	
	[responseData release];
	
	[self performSelectorOnMainThread:@selector(reloadTableView:) withObject:inServerSections waitUntilDone:NO];
	
}
-(void)reloadTableView:(NSArray *)newSetions{
	[self.enableSections removeAllObjects];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	for (Section *serverSection in newSetions) {
		BOOL added = NO;	
		for (Section *mySection in delegate.user.mySections ) {
			if ([mySection.sectionId isEqualToString:serverSection.sectionId] ) {
				//NSLog(@"mysectionid=%@,serverSectionid=%@",mySection.sectionId,serverSection.sectionId);
				added = YES;
			}
		}
		if (!added) {
			[self.enableSections addObject:serverSection];
		}
	}
	[self.tableView reloadData];
	
	[self.selectedSection removeAllObjects];
	
}
#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.enableSections count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"EnabledCell";
    
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
	NSInteger index = [indexPath row];
    Section *section = [self.enableSections objectAtIndex:index];
	
	cell.textLabel.text = section.sectionName;
	cell.detailTextLabel.text = section.summary;
	
	//cell.imageView = 
    // Configure the cell...
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
	NSString *rowStr = [[NSString alloc] initWithFormat:@"%d",[indexPath row]];
	if ([self.selectedSection  objectForKey:rowStr]) {
		[self.selectedSection removeObjectForKey:rowStr];
		cell.accessoryType = UITableViewCellAccessoryNone;
	}else {
		[self.selectedSection setObject:[self.enableSections objectAtIndex:[indexPath row]] forKey:rowStr];
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	}

}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	
	[self.enableSections release];
	[self.selectedSection release];
	[self.tableView release];
    [super dealloc];
}


@end

